# 处理项目请求

from flask import Blueprint

bp = Blueprint('main',__name__)

from flask import request,jsonify,make_response,current_app,redirect
from app.modules import Payload,Category,Session,Project,Record
from functools import wraps
from app.exceptions import MsgError
from app.parsers import urlencode,urldecode
import time
import base64
from app.api.websocket import update_base_info

# 处理访问项目地址的请求

@bp.route('/<re("[0-9a-zA-Z/]+"):address>',methods=['GET','POST','OPTIONS'])
def index(address):
    address = urldecode(address)
    index = address.find('/')
    real_address = address
    if index != -1:
        real_address = address[:index]
    project = Project.get_project_by_address(real_address)
    if project is None:
        return redirect('/404')

    response = make_response('')
    
    if not (address == project.config['address'] and request.method == 'GET' and len(request.args)<1):
        # 如果不是请求静态xss代码，则产生记录
        record = {}
        record['belong_to_project'] = project.id
        record['risk_level'] = 0
        record['checked'] = 0
        record['timestamp'] = int(time.time())
        req_info = {}
        req_info['method'] = request.method
        req_info['path'] = request.url
        header = []
        # print(request.headers.to_list())
        for i in request.headers.to_list():
            header.append(list(i))
        req_info['header'] = header
        params = []
        for i in request.args.to_dict():
            tmp = []
            tmp.append(i)
            tmp.append(request.args.get(i))
            tmp.append('GET参数')
            params.append(tmp)
        for i in request.form.to_dict():
            tmp = []
            tmp.append(i)
            tmp.append(request.form.get(i))
            tmp.append('POST参数')
            params.append(tmp)
        req_info['params'] = params
        req_info['raw_data'] = base64.b64encode(request.get_data(parse_form_data=False)).decode('utf8',errors='ignore')
        req_info['remote_ip'] = request.remote_addr
        record['req_info'] = req_info
        tmp = Record.create_record_by_json(record)
        update_base_info('record','add',[tmp.to_json()])
    else:
        # 请求静态xss代码，返回数据
        response = make_response(project.get_code())
        for i in project.config['extra_response_header']:
            response.headers[i[0]] = i[1]
    # 跨域
    response.headers["Access-Control-Allow-Origin"]="*"
    response.headers["Access-Control-Allow-Methods"]="*"
    response.headers["Access-Control-Allow-Headers"]="*"
    response.headers["Access-Control-Expose-Headers"]="*"
    return response